package com.aduerr.v1shouyin.mvp.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.*;
import android.widget.*;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;
import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.entity.IntegralEntity;
import com.aduerr.v1shouyin.entity.MemberInfoEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.mvp.widget.BasedDialog;
import com.aduerr.v1shouyin.util.SharedPreferencesUtils;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.aduerr.v1shouyin.view.SecurityCodeView;
import com.bumptech.glide.Glide;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.HashMap;


/**
 * @author HI
 * @email dev1024@foxmail.com
 * @time 2018/10/25 11:38
 * @change
 * @chang time
 * @class describe
 */

public class VIPIntegralActivity extends AppCompatActivity {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_discount_card)
    TextView tvDiscountCard;
    @BindView(R.id.tv_vip_name)
    TextView tvVipName;
    @BindView(R.id.tv_phone_card)
    TextView tvPhoneCard;
    @BindView(R.id.tv_integral)
    TextView tvIntegral;
    @BindView(R.id.et_integral)
    EditText etIntegral;
    @BindView(R.id.rb_charge)
    RadioButton rbCharge;
    @BindView(R.id.rb_use)
    RadioButton rbUse;
    @BindView(R.id.rb_clear)
    RadioButton rbClear;
    @BindView(R.id.imageview_icon)
    CircleImageView imageviewIcon;
    @BindView(R.id.tv_comfirm)
    TextView tvComfirm;
    SweetAlertDialog pDialog;
    //=================================================输入密码的控件
    Dialog dialog;
    SecurityCodeView securityCodeView;
    private String scanMemberNo;
    private MemberInfoEntity memberInfoEntity;
    private BasedDialog.Builder builder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vip_integral);
        ButterKnife.bind(this);
        tvTitle.setText("会员积分");
        initDate();
    }

    private void initDate() {
        Intent intent = getIntent();
        if(intent != null) {
            // intent.putExtra("scanMemberNo", erWeiMaResult);
            scanMemberNo = intent.getStringExtra("scanMemberNo");

            memberInfoEntity = (MemberInfoEntity) intent.getSerializableExtra(
                    "memberinfo");
            tvPhoneCard.setText("ID：" + memberInfoEntity.getData().getNO());
            tvVipName.setText(memberInfoEntity.getData().getNames());
            tvIntegral.setText(memberInfoEntity.getData().getIntegral());
            tvDiscountCard.setText(memberInfoEntity.getData().getLevelName() + "  " + memberInfoEntity.getData().getDiscount());
            Glide.with(VIPIntegralActivity.this).load(memberInfoEntity.getData().getHeadImgUrl()).into(imageviewIcon);
        }
    }

    @OnClick({R.id.img_back, R.id.tv_comfirm, R.id.rb_charge, R.id.rb_use, R.id.rb_clear})
    public void onViewClicked(View view) {
        switch(view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.rb_charge:
                if(rbCharge.isChecked())
                    tvComfirm.setText("确认充值");
                break;
            case R.id.rb_use:
                if(rbUse.isChecked())
                    tvComfirm.setText("确认使用");
                break;
            case R.id.rb_clear:
                if(rbClear.isChecked())
                    tvComfirm.setText("确认清零");
                break;
            case R.id.tv_comfirm:
                if(rbCharge.isChecked()) {
                    if(TextUtils.isEmpty(etIntegral.getText().toString())) {
                        ToastUtils.showToast(VIPIntegralActivity.this, "请输入积分");
                        return;
                    }
                    inPutPass();
                } else if(rbUse.isChecked()) {
                    if(TextUtils.isEmpty(etIntegral.getText().toString())) {
                        ToastUtils.showToast(VIPIntegralActivity.this, "请输入积分");
                        return;
                    }
                    integralToPay(etIntegral.getText().toString(), scanMemberNo, 2);
                } else if(rbClear.isChecked()) {
                    if(memberInfoEntity.getData().getIntegral().equals("0")) {
                        ToastUtils.showToast(VIPIntegralActivity.this, "当前积分为0，无法清零");
                        return;
                    }
                    integralToPay(tvIntegral.getText().toString(), scanMemberNo, 3);
                }

                break;
        }
    }

    private void inPutPass() {
        View view =
                LayoutInflater.from(VIPIntegralActivity.this).inflate(R.layout.dialog_tuikuan, null);
        // 对话框
        dialog = new Dialog(VIPIntegralActivity.this);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.show();
        // 设置宽度为屏幕的宽度
        WindowManager windowManager = this.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) (display.getWidth()); // 设置宽度
        dialog.getWindow().setAttributes(lp);
        dialog.getWindow().setContentView(view);
        //==================================弹出键盘================================================================
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        //===========================================================================================================
        //findview
        //找到自定义的控件用来显示密码
        securityCodeView = (SecurityCodeView) view.findViewById(R.id.scv_edittext);
        TextView dialogui_tv_title = (TextView) view.findViewById(R.id.dialogui_tv_title);
        dialogui_tv_title.setText("请输入充值密码");
        securityCodeView.setInputCompleteListener(new SecurityCodeView.InputCompleteListener() {
            @Override
            public void inputComplete() {
                dialog.hide();
                memberIntegral(etIntegral.getText().toString(), scanMemberNo, 1,
                        securityCodeView.getEditContent());
            }

            @Override
            public void deleteContent(boolean isDelete) {
                //DO NO THING
            }
        });
    }

    private void integralToPay(String strIntegral, String strScanMemberID, int type) {
        View view =
                LayoutInflater.from(VIPIntegralActivity.this).inflate(R.layout.dialog_jifen, null);
        TextView dialoguiTvTitle = (TextView) view.findViewById(R.id.dialogui_tv_title);
        Button confirm_btn = (Button) view.findViewById(R.id.confirm_btn);
        Button confirm_cancel = (Button) view.findViewById(R.id.cancel_btn);
        TextView jifen = (TextView) view.findViewById(R.id.jifen);

        confirm_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                memberIntegral(strIntegral, strScanMemberID, type);
                dialog.cancel();
            }
        });
        confirm_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();
            }
        });
        jifen.setText(strIntegral);
        if(type == 2) {
            dialoguiTvTitle.setText("积分消费");
        } else if(type == 3) {
            dialoguiTvTitle.setText("积分清零");
        }

        // 对话
        dialog = new Dialog(VIPIntegralActivity.this);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.show();
        // 设置宽度为屏幕的宽度
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) (display.getWidth() * 0.8); // 设置宽度
        dialog.getWindow().setAttributes(lp);
        dialog.getWindow().setContentView(view);
    }

    private void memberIntegral(String strIntegral, String strScanMemberID, int type) {
        memberIntegral(strIntegral, strScanMemberID, type, "");
    }

    private void memberIntegral(String strIntegral, String strScanMemberID, int type,
                                String password) {

        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("addintegral", strIntegral);
        addParams.put("scanMemberNo", strScanMemberID);
        addParams.put("type", type + "");//1充值 2消费 3清零，只有充值才需要密码
        addParams.put("password", password);
        APIRetrofit.getAPIService().memberIntegral(RXRequest.getXingPosParams(addParams
                , this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<IntegralEntity>() {

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        if(pDialog == null) {
                            pDialog = new SweetAlertDialog(VIPIntegralActivity.this,
                                    SweetAlertDialog.PROGRESS_TYPE);
                            pDialog.getProgressHelper().setBarColor(Color.parseColor(
                                    "#005fee"));
                            pDialog.setTitleText("请稍等...");
                            pDialog.setCancelable(false);
                            pDialog.show();
                        }
                    }


                    @Override
                    public void onNext(IntegralEntity integralEntity) {

                        if(integralEntity.getSuccess() == 1) {
                            if(type == 3) {
                                ToastUtils.showToast(VIPIntegralActivity.this, "清零成功");
                            } else {
                                Intent intent = new Intent(VIPIntegralActivity.this,
                                        VipIntegralDetailActivity.class);
                                intent.putExtra("type", type);
                                intent.putExtra("data", integralEntity.getData());
                                startActivity(intent);
                            }
                            finish();
                        } else {
                            ToastUtils.showToast(VIPIntegralActivity.this,
                                    integralEntity.getErrMsg());
                        }
                    }

                    @Override
                    public void onComplete() {
                        pDialog.dismiss();
                        pDialog = null;
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        ToastUtils.showToast(VIPIntegralActivity.this,
                                e.getMessage().toString() + "");
                        pDialog.dismiss();
                        pDialog = null;
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(VIPIntegralActivity.this, "网络连接超时",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(VIPIntegralActivity.this, "连接失败",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof UnknownHostException) {
//                            Log.e("onError:", "error:-----" + e.getMessage());//R
//                            .string.checknet +
                            Toast.makeText(VIPIntegralActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        } else {
//                            Log.e("onError:", "error:" + e.getMessage());//R.string
//                            .checknet +
                            Toast.makeText(VIPIntegralActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }

                });

    }

    public void useIntegral(String strIntegral, String strScanMemberID) {
        HashMap<String, String> map = new HashMap<>();
        map.put("integral", strIntegral);
        map.put("ScanMemberID", strScanMemberID);
        APIRetrofit.getAPIService().integralToPay(RXRequest.getXingPosParams(map,
                VIPIntegralActivity.this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<IntegralEntity>() {

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        if(pDialog == null) {
                            pDialog = new SweetAlertDialog(VIPIntegralActivity.this,
                                    SweetAlertDialog.PROGRESS_TYPE);
                            pDialog.getProgressHelper().setBarColor(Color.parseColor(
                                    "#005fee"));
                            pDialog.setTitleText("请稍等...");
                            pDialog.setCancelable(false);
                            pDialog.show();
                        }
                    }


                    @Override
                    public void onNext(IntegralEntity integralEntity) {

                        if(integralEntity.getSuccess() == 1) {
                            Intent intent = new Intent(VIPIntegralActivity.this,
                                    VipIntegralDetailActivity.class);
                            intent.putExtra("type", 1);
                            intent.putExtra("data", integralEntity.getData());
                            startActivity(intent);
                            finish();
                        } else {
                            ToastUtils.showToast(VIPIntegralActivity.this,
                                    integralEntity.getErrMsg());
                        }
                    }

                    @Override
                    public void onComplete() {
                        pDialog.dismiss();
                        pDialog = null;
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        ToastUtils.showToast(VIPIntegralActivity.this,
                                e.getMessage().toString() + "");
                        pDialog.dismiss();
                        pDialog = null;
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(VIPIntegralActivity.this, "网络连接超时",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(VIPIntegralActivity.this, "连接失败",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof UnknownHostException) {
//                            Log.e("onError:", "error:-----" + e.getMessage());//R
//                            .string.checknet +
                            Toast.makeText(VIPIntegralActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        } else {
//                            Log.e("onError:", "error:" + e.getMessage());//R.string
//                            .checknet +
                            Toast.makeText(VIPIntegralActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }

                });


    }

    private void chargeIntegral(String erWeiMaResult, String operatePass) {
        if(TextUtils.isEmpty(erWeiMaResult)) return;
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("ScanMemberID", erWeiMaResult);
        addParams.put("integral", etIntegral.getText().toString());
        addParams.put("operatePass", operatePass);
        APIRetrofit.getAPIService().addIntegral(RXRequest.getXingPosParams(addParams,
                VIPIntegralActivity.this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<IntegralEntity>() {

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        if(pDialog == null) {
                            pDialog = new SweetAlertDialog(VIPIntegralActivity.this,
                                    SweetAlertDialog.PROGRESS_TYPE);
                            pDialog.getProgressHelper().setBarColor(Color.parseColor(
                                    "#005fee"));
                            pDialog.setTitleText("正在充值中");
                            pDialog.setCancelable(false);
                            pDialog.show();
                        }
                    }

                    @Override
                    public void onNext(@NonNull IntegralEntity integralEntity) {
                        int success = integralEntity.getSuccess();
                        if(success == 1) {
                            IntegralEntity.DataBean data = integralEntity.getData();
                            if(data != null) {
                                Intent intent = new Intent(VIPIntegralActivity.this,
                                        VipIntegralDetailActivity.class);
                                intent.putExtra("type", 0);
                                intent.putExtra("data", integralEntity.getData());
                                startActivity(intent);
                                finish();
                            } else {

                            }
                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            SharedPreferencesUtils.remove(VIPIntegralActivity.this,
                                    "autologin");
                            SharedPreferencesUtils.remove(VIPIntegralActivity.this,
                                    "remberpassword");
                            startActivity(new Intent(VIPIntegralActivity.this,
                                    BangGuidActivity.class));
                            finish();
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(integralEntity.getErrMsg());
                        } else if(success == -3) {//充值密码错误
                            ToastUtils.showToast(VIPIntegralActivity.this,
                                    integralEntity.getErrMsg() + "");
                        } else {
                            ToastUtils.showToast(VIPIntegralActivity.this,
                                    integralEntity.getErrMsg() + "");

                        }
                    }

                    @Override
                    public void onComplete() {
                        pDialog.dismiss();
                        pDialog = null;
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        ToastUtils.showToast(VIPIntegralActivity.this,
                                e.getMessage().toString() + "");
                        pDialog.dismiss();
                        pDialog = null;
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(VIPIntegralActivity.this, "网络连接超时",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(VIPIntegralActivity.this, "连接失败",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof UnknownHostException) {
//                            Log.e("onError:", "error:-----" + e.getMessage());//R
//                            .string.checknet +
                            Toast.makeText(VIPIntegralActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        } else {
//                            Log.e("onError:", "error:" + e.getMessage());//R.string
//                            .checknet +
                            Toast.makeText(VIPIntegralActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }

                });
    }
}
